<!--  -->
<template>
  <div>
    <panel></panel>
    <div class="layui-container">
      <div class="layui-row layui-col-space15">
        <div class="layui-col-md8 content detail">
          <div class="fly-panel detail-box">
            <h1>{{ page.title }}</h1>
            <div class="fly-detail-info">
              <!-- <span class="layui-badge">审核中</span> -->
              <span
                class="layui-badge layui-bg-green fly-detail-column"
                v-if="page.catalog === 'logs'"
                >动态</span
              >
              <span
                class="layui-badge layui-bg-green fly-detail-column"
                v-else-if="page.catalog === 'share'"
                >分享</span
              >
              <span
                class="layui-badge layui-bg-green fly-detail-column"
                v-else-if="page.catalog === 'ask'"
                >提问</span
              >
              <span
                class="layui-badge layui-bg-green fly-detail-column"
                v-else-if="page.catalog === 'advise'"
                >建议</span
              >
              <span
                class="layui-badge layui-bg-green fly-detail-column"
                v-else-if="page.catalog === 'discuss'"
                >交流</span
              >
              <span
                class="layui-badge layui-bg-green fly-detail-column"
                v-else-if="page.catalog === 'notice'"
                >公告</span
              >
              <span
                class="layui-badge"
                style="background-color: #999"
                v-if="parseInt(page.isEnd) === '0'"
                >未结</span
              >
              <span class="layui-badge" style="background-color: #5fb878" v-else
                >已结</span
              >
              <span
                class="layui-badge layui-bg-black"
                v-show="page.isTop === '1'"
                >置顶</span
              >
              <span v-for="(tag, index) in page.tags" :key="'tags' + index">
                <span
                  class="layui-badge layui-bg-red"
                  v-if="tag.length !== 0 ? tag.name : false"
                  :class="tag.class"
                  >{{ tag.name }}</span
                >
              </span>
              <div v-hasRole="'admin'" class="fly-admin-box">
                <div data-id="123">
                  <span
                    v-hasPermission="['get', 'delete']"
                    class="layui-btn layui-btn-xs jie-admin"
                    type="del"
                    >删除</span
                  >
                  <span
                    @click="isTop(page)"
                    class="layui-btn layui-btn-xs jie-admin"
                    type="set"
                    field="stick"
                    rank="1"
                    >置顶</span
                  >
                  <!-- <span class="layui-btn layui-btn-xs jie-admin" type="set" field="stick" rank="0" style="background-color:#ccc;">取消置顶</span> -->

                  <span
                    @click="addTag(page)"
                    class="layui-btn layui-btn-xs jie-admin"
                    type="set"
                    field="status"
                    rank="1"
                    >加精</span
                  >
                  <!-- <span class="layui-btn layui-btn-xs jie-admin" type="set" field="status" rank="0" style="background-color:#ccc;">取消加精</span> -->
                </div>
              </div>
              <span class="fly-list-nums">
                <a href="#comment"
                  ><i class="iconfont" title="回答">&#xe60c;</i>
                  {{ page.answer }}</a
                >
                <i class="iconfont" title="人气">&#xe60b;</i> {{ page.reads }}
              </span>
            </div>
            <!-- 作者信息 -->
            <div class="detail-about">
              <!-- {{ page.user ? page.user.pic : 'pic test' }} -->
              <a class="fly-avatar" href="../user/home.html">
                <img
                  :src="
                    page.user
                      ? page.user.pic
                      : 'http://localhost:3000/images/avatar/1.jpg'
                  "
                />
              </a>
              <div class="fly-detail-user">
                <a href="../user/home.html" class="fly-link">
                  <cite>{{ page.user ? page.user.name : 'dnm' }}</cite>
                  <!-- <i class="iconfont icon-renzheng" title="认证信息：{{ rows.user.approve }}"></i> -->
                  <!-- <i class="iconfont icon-renzheng" title="认证信息："></i> -->
                  <i
                    class="layui-badge fly-badge-vip"
                    v-if="page.user ? page.user.isVip : false"
                    >{{ 'VIP' + page.user.isVip }}</i
                  >
                </a>
                <span>{{ page.created | moment }}</span>
              </div>
              <div class="detail-hits">
                <span style="padding-right: 10px; color: #ff7200"
                  >悬赏:{{ page.fav }}</span
                >
              </div>
            </div>
            <div class="layui-btn-content fly-detail-admin">
              <router-link
                :to="{ name: 'edit', params: { tid: tid, page: page } }"
                v-show="page.isEnd === '0' && page.user._id === user._id"
                class="layui-btn layui-btn-sm jie-admin"
                >编辑</router-link
              >
              <a
                class="layui-btn layui-btn-sm jie-admin jie-admin-collect"
                @click.prevent="collect(page)"
                :class="{ 'layui-btn-primary': page.isFav === '1' }"
                >{{ page.isFav ? '取消收藏' : '收藏' }}</a
              >
            </div>
            <div class="detail-body photos" v-html="content"></div>
          </div>

          <div class="fly-panel detail-box" id="flyReply">
            <fieldset
              class="layui-elem-field layui-field-title"
              style="text-align: center"
            >
              <legend>回帖</legend>
            </fieldset>

            <ul class="jieda" id="jieda">
              <li
                class="jieda-daan"
                v-for="(item, index) in comments"
                :key="'comments' + index"
              >
                <div class="detail-about detail-about-reply">
                  <a class="fly-avatar" href="">
                    <img
                      :src="
                        item.cuid
                          ? item.cuid.pic
                          : 'http://localhost:3000/images/avatar/1.jpg'
                      "
                    />
                  </a>
                  <div class="fly-detail-user">
                    <a href="" class="fly-link">
                      <cite>{{ item.cuid ? item.cuid.name : 'mfh' }}</cite>
                      <i
                        class="layui-badge fly-badge-vip"
                        v-if="
                          item.cuid && item.cuid.isVip !== '0'
                            ? item.cuid.isVip
                            : false
                        "
                        >{{ 'VIP' + item.cuid.isVip }}</i
                      >
                    </a>

                    <span v-if="index === 0">(楼主)</span>

                    <!-- <span v-else-if="index === 1" style="color: #5fb878"
                      >(管理员)</span
                    > -->
                    <!-- <span style="color:#FF9E3F">（社区之光）</span>
                  <span style="color:#999">（该号已被封）</span> -->
                  </div>

                  <div class="detail-hits">
                    <span>{{ item.created | moment }}</span>
                  </div>

                  <i
                    v-if="item.isBest === '1'"
                    class="iconfont icon-caina"
                    title="最佳答案"
                  ></i>
                </div>
                <!--  class里 v-html="item.content" 转换全局directives-->
                <div
                  class="detail-body jieda-body photos"
                  v-richtext="item.content"
                ></div>
                <div class="jieda-reply">
                  <span
                    class="jieda-zan"
                    :class="{ zanok: item.handed === '1' }"
                    type="zan"
                    @click="hands(item)"
                  >
                    <i class="iconfont icon-zan"></i>
                    <em>{{ item.hands }}</em>
                  </span>
                  <span type="reply" @click="reply(item)">
                    <i class="iconfont icon-svgmoban53"></i>
                    回复
                  </span>
                  <div class="jieda-admin">
                    <span
                      type="edit"
                      v-show="page.isEnd === '0' && item.cuid._id === user._id"
                      @click="editComment(item)"
                      >编辑</span
                    >
                    <!-- <span type="del">删除</span> -->
                    <span
                      v-show="page.isEnd === '0' && item.cuid._id !== user._id"
                      class="jieda-accept"
                      type="accept"
                      @click="setBest(item)"
                      >采纳</span
                    >
                  </div>
                </div>
              </li>

              <!-- 无数据时 -->
              <li class="fly-none" v-if="comments.length === 0">消灭零回复</li>
            </ul>
            <pagination
              v-show="total > 0"
              :showType="'text'"
              :hasSelect="true"
              :total="total"
              :size="size"
              :current="current"
              :showEnd="true"
              :hasTotal="true"
              @changeCurrent="handelChange"
              @changeLimit="handelLimit"
            ></pagination>
            <div class="layui-form layui-form-pane">
              <validation-observer ref="observer" v-slot="{ validate }">
                <editor
                  @changeContent="addContent"
                  :initContent="editinfo.content"
                ></editor>
                <div class="sp">
                  <div class="layui-form-item">
                    <input type="hidden" name="jid" value="123" />
                    <button
                      class="layui-btn"
                      type="button"
                      @click="validate().then(submit)"
                    >
                      提交回复
                    </button>
                  </div>
                  <div class="layui-form-item code">
                    <validation-provider
                      name="code"
                      ref="codefield"
                      rules="required|length:4"
                      v-slot="{ errors }"
                    >
                      <div class="layui-row row">
                        <label
                          for="L_vercode"
                          ref="observer2"
                          class="layui-form-label"
                          >验证码</label
                        >
                        <div class="layui-input-inline">
                          <input
                            type="text"
                            name="code"
                            v-model="code"
                            placeholder="请输入验证码"
                            autocomplete="off"
                            class="layui-input"
                          />
                        </div>
                        <div class="code">
                          <span
                            class="svg"
                            style="color: #c00"
                            @click="_getCode()"
                            v-html="svg"
                          ></span>
                        </div>
                      </div>
                      <div class="layui-form-mid">
                        <span style="color: #c00">{{ errors[0] }}</span>
                      </div>
                    </validation-provider>
                  </div>
                </div>
              </validation-observer>
            </div>
          </div>
        </div>
        <div class="layui-col-md4">
          <hot-list></hot-list>
          <ads></ads>
          <div class="fly-panel" style="padding: 20px 0; text-align: center">
            <img
              src="@/assets/images/weixin.jpg"
              style="max-width: 100%"
              alt="layui"
            />
            <p style="position: relative; color: #666">
              微信扫码关注 爱陌 公众号
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Panel from "@/components/Panel.vue";
import HotList from "@/components/sidebar/HotList.vue";
import Ads from "@/components/sidebar/Ads.vue";
import Editor from "../modules/editor/Index";
import mixin from "@/mixin/code";
import Pagination from "@/components/modules/pagination/Index";
import { escapeHtml } from "@/utils/escapeHtml";
import { getDetail, setCollect, addTop, addTags } from "@/api/content";
import {
  addComment,
  getComents,
  updataComment,
  addBest,
  setHands,
} from "@/api/comment";
// import { scrollToElem } from "@/utils/common";
import { ValidationProvider, ValidationObserver } from "vee-validate";
export default {
  name: "detail",
  mixins: [mixin],
  components: {
    HotList,
    Ads,
    Panel,
    Editor,
    mixin,
    ValidationProvider,
    ValidationObserver,
    Pagination,
  },
  data () {
    return {
      tid: this.$route.params.tid,
      total: 0,
      size: 10,
      current: 0,
      page: "",
      comments: "",
      editinfo: {
        content: "",
        code: "",
        sid: "",
      },
    };
  },

  computed: {
    user () {
      return this.$store.state.userInfo;
    },
    content () {
      if (typeof this.page.content === "undefined") {
        return "";
      }
      if (this.page.content.trim() === "") {
        return "";
      }
      return escapeHtml(this.page.content);
    },
  },
  mounted () {
    // window.vue = scrollToElem
    this.getPostDetail();
    this.getCommentsList();
  },
  methods: {
    //置顶
    isTop (item) {
      console.log(item);
      addTop({
        tid: item._id,
        uid: this.$store.state.userInfo._id
      }).then((res) => {
        if (res.code === 200) {
          this.$pop('', '置顶成功')
        } else {
          this.$pop('shake', '非管理员禁止操作')
        }
      })
    },
    //加精
    addTag (item) {
      addTags({
        tid: item._id,
        uid: this.$store.state.userInfo._id
      }).then((res) => {
        if (res.code === 200) {
          this.$pop('', '加精成功')
        } else {
          this.$pop('shake', '非管理员禁止操作')
        }
      })
    },
    //添加评论
    addContent (val) {
      this.editinfo.content = val;
    },
    async submit () {
      const isValid = await this.$refs.observer.validate();
      if (!isValid) {
        return;
      }
      const content = this.editinfo.content;
      if (content.trim() === "") {
        this.$alert("内容为空");
        return;
      }
      const isLogin = this.$store.state.isLogin;
      if (!isLogin) {
        this.$pop("shake", "请先登录");
        return;
      }
      const user = this.$store.state.userInfo;
      this.editinfo.code = this.code;
      this.editinfo.sid = this.$store.state.sid;
      this.editinfo.tid = this.tid;
      //获取评论用户信息
      const cuid = {
        name: user.name,
        pic: user.pic,
        _id: user._id,
        isVip: user.isVip,
      };
      if (
        typeof this.editinfo.cid !== "undefined" &&
        this.editinfo.cid !== ""
      ) {
        //判断是否修改
        if (this.editinfo.content === this.editinfo.item.content) {
          this.$pop("shake", "原来内容不能与现在相同");
          return;
        }
        //删除前端每次传item
        const obj = { ...this.editinfo };
        delete obj["item"];
        updataComment(obj).then((res) => {
          if (res.code === 200) {
            const temp = this.editinfo.item;
            temp.content = this.editinfo.content;
            this.$alert("更新评论成功");
            this.code = "";
            this.editinfo.content = "";
            // res.data.cuid = cuid
            this.comments.splice(
              this.comments.indexOf(this.editinfo.item),
              1,
              temp
            );
          }
        });
        return;
      }
      //添加评论请求
      addComment(this.editinfo).then((res) => {
        if (res.code === 200) {
          this.$alert("添加评论成功");
          this.code = "";
          this.editinfo.content = "";
          res.data.cuid = cuid;
          this.comments.push(res.data);
          this._getCode();
        }
        if (res.code === 500) {
          this._getCode();
          this.$refs.codefield.setErrors([res.msg]);
        }
        if (res.code === 501) {
          this.$pop("shake", "用户已经禁言，请联系管理员");
        }
      });
    },
    //获取文章id
    getPostDetail () {
      getDetail({ tid: this.tid }).then((res) => {
        if (res.code === 200) {
          this.$store.commit("setTid", this.$route.params.tid);
          this.page = res.data;
          console.log(res.data);
        }
      });
    },
    //评论列表
    getCommentsList () {
      getComents({
        tid: this.tid,
        page: this.current,
        limit: this.size
      }).then((res) => {
        // console.log(res);
        this.comments = res.data;
        this.total = res.total;
      });
    },
    //页面page跳转
    handelChange (val) {
      this.current = val;
      this.getCommentsList()
    },
    //页面大小
    handelLimit (val) {
      this.size = val
      this.getCommentsList()
    },
    //编辑评论
    editComment (item) {
      this.editinfo.content = item.content;
      this.editinfo.cid = item._id;
      this.editinfo.item = item;
      document.getElementById('edit').focus()
    },
    //采纳
    setBest (item) {
      this.$confirm(
        "确定采纳为最佳答案吗？",
        () => {
          //发送请求
          console.log(item);
          addBest(item).then((res) => {
            if (res.code === 200) {
              this.$alert("采纳成功");
              item.isBest = "1";
              this.page.isEnd = "1";
            }
          });
        },
        () => { }
      );
    },
    hands (item) {
      // cuid: item.cuid._id被评论的人
      setHands({ cid: item._id, cuid: item.cuid._id }).then((res) => {
        if (res.code === 200) {
          item.handed = '1';
          item.hands += 1
        } else {
          this.$pop('shake', '你已经点过赞了,请手下留情')
        }
      });
    },
    reply (item) {
      //插入@符号+nmae 到con
      //滚动
      //foucs
      const reg = /^@[\S]+/g
      // debugger
      if (this.editinfo.content) {
        if (reg.test(this.editinfo.content)) {
          this.editinfo.content = this.editinfo.content.replace(reg, '@' + item.cuid.name + '')
        } else {
          //评论非空
          if (this.editinfo.content !== '') {
            this.editinfo.content = `@${item.cuid.name} ${this.editinfo.content}`
          }
        }
      } else {
        //为空
        this.editinfo.content = '@' + item.cuid.name + '';
      }
      document.getElementById('edit').focus()
      console.log(item);
    },
    collect (item) {
      const isLogin = this.$store.state.isLogin
      if (isLogin) {
        const tid = this.$store.state.tid
        const uid = this.$store.state.userInfo._id
        setCollect(
          {
            uid: uid,
            tid: tid,
            title: item.title,
            isFav: this.page.isFav ? 0 : 1
          }
        ).then((res) => {
          if (res.code === 200) {
            this.page.isFav = !this.page.isFav
            console.log(this.page.isFav);
            this.$pop('', this.page.isFav ? '设置成功' : '取消收藏成功')
          }
        })
      } else {
        this.$alert('用户未登陆！')
      }


    }
  },
};
</script>
<style scoped lang="scss">
.fly-detail-admin {
  padding-top: 10px;
  text-align: right;
  border-top: 1px dotted #eaeaea;
  background-color: #f8f8f8;
}
.fly-detail-info span {
  margin-right: 5px;
}
.sp {
  display: flex;
  justify-content: space-between;
}
.code {
  display: inline-block;
}
</style>
